#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include "idc_ubus_common.h"
#include "idc_ubus.h"
#include "idc_ubus_mqtt.h"
#include "data_type.h"

const struct blobmsg_policy lora_addr_policy[] = {
        [0] = { .name = "addr", .type = BLOBMSG_TYPE_INT32 },
        [1] = { .name = "group_addr", .type = BLOBMSG_TYPE_INT32 },
        [2] = { .name = "is_center", .type = BLOBMSG_TYPE_INT32 },
}; 

static const struct ubus_method idc_methods[] = {
        UBUS_METHOD("energy_info", energy_info, enerty_info_policy),
        UBUS_METHOD("send", send, send_policy),
}; 
static struct ubus_object_type idc_object_type =  UBUS_OBJECT_TYPE("sihan.mqtt", idc_methods);
 
 
static struct ubus_object idc_object = {
        .name = "sihan.mqtt",
        .type = &idc_object_type,
        .methods = idc_methods,
        .n_methods = ARRAY_SIZE(idc_methods)
};
void get_lora_addr_callback(struct ubus_request *req, int type, struct blob_attr *msg) {
        if (!msg) {
                return;
        }
        struct blob_attr *tb[3];
        blobmsg_parse(lora_addr_policy, ARRAY_SIZE(lora_addr_policy), tb, blobmsg_data(msg), blobmsg_data_len(msg));
        if(tb[0]){
                runCfg.lora_addr = blobmsg_get_u32(tb[0]);
        }
        if(tb[1]){
                runCfg.lora_group = blobmsg_get_u32(tb[1]);
        }
        printf("lora_addr:%04X,lora_group:%04X\n", runCfg.lora_addr, runCfg.lora_group);
}
/**
 * 调用Energy服务,获取Lora地址信息
 */
int ubus_invoke_get_lora_addr(struct ubus_context *ctx) {
    // 查找 network.device 的 ID
    uint32_t obj_id;
    if (ubus_lookup_id(ctx, "sihan.energy", &obj_id) != 0) {
        fprintf(stderr, "Failed to lookup sihan.energy\n");
        ubus_free(ctx);
        return -1;
    }

    blob_buf_init(&b, 0);
    
    // 发起异步调用
    int ret = ubus_invoke(ctx, obj_id, "query_addr", b.head, get_lora_addr_callback, 0, 3000);
    if (ret == 0) {
        
    }
    // 清理资源
    blob_buf_free(&b);
    return 0;
}
int ubus_doing()
{
        int ret;
 
        ctx = ubus_connect(NULL);
        if (!ctx) {
                fprintf(stderr, "Failed to connect to ubus\n");
                return -1;
        }

        ubus_invoke_get_lora_addr(ctx); //初始化获取其它服务的数据

        ubus_add_uloop(ctx);
 
        ret = ubus_add_object(ctx, &idc_object);
        if (ret)
                fprintf(stderr, "Failed to add object: %s\n", ubus_strerror(ret));
}
void *ubus_worker(void *arg)
{
        int ret;
        printf("idc_ubus_mqtt_init\n");
        uloop_init();
        ubus_doing();
        uloop_run();
 
        ubus_free(ctx);
        uloop_done();    
}
